package com.changgou.web.controller;


import com.changgou.entity.Result;
import com.changgou.order.feign.CartFeign;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import com.changgou.user.feign.AddressFeign;
import com.changgou.user.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller

@RequestMapping("/worder")
public class OrderController {


    @Autowired
    private AddressFeign addressFeign;


    @Autowired
    private CartFeign cartFeign;


    @RequestMapping("/ready/order")
    public String readyOrder(Model model){

        //1.收件人的信息

        //获取到地址集合
        List<Address> addressList = addressFeign.list().getData();


        model.addAttribute("address",addressList);

        //购物车信息

        /**
         * map  中包含
         *
         * 购物车的数据列表
         * 购物车的总数量
         * 购物车的总价格
         */
        Map map = cartFeign.list();

        //获取到购物车数据
        List<OrderItem> orderItemList= (List<OrderItem>) map.get("orderItemList");

        //获取购物车总金额
        Integer totalMoney= (Integer) map.get("totalMoney");

        //获取总数量
        Integer totalNum = (Integer) map.get("totalNum");


        model.addAttribute("carts",orderItemList);

        model.addAttribute("totalMoney",totalMoney);

        model.addAttribute("totalNum",totalNum);


        //加载默认收件人信息
        for (Address address : addressList) {
            if ("1".equals(address.getIsDefault())){


                //默认收件人
                model.addAttribute("deAddr",address);
                break;
            }

        }
        return "order";
    }


    @Autowired
    private OrderFeign orderFeign;


    /**
     *
     *      保存订单的实现
     * @param order
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody Order order){
        Result result = orderFeign.add(order);

        return result;

    }

}
